const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const { exec } = require('../db/index')

// 1. 博客查询接口
router.get('/api/blogs', async (ctx, next) => {
	// const { id } = ctx.state.userInfo
	// 接收参数
	const { page = 1, size = 10 } = ctx.query
	// 处理参数
	const list = await exec(
		`select * from blogs where status=1 limit ? offset ?`,
		[size * 1, (page - 1) * size]
	)
	const [count] = await exec(
		`select count(id) as count from blogs where status=1 `
	)
	// 返回数据
	ctx.body = {
		code: 0,
		msg: 'succes',
		data: { list, count: count.count }
	}
})

// 2. 博客添加接口
router.post('/api/blogs', async (ctx, next) => {
	// 接收参数
	const {
		title,
		content,
		userId = ctx.state.userInfo.id,
		comments = ''
	} = ctx.request.body
	// 处理
	const insertData = await exec(
		`insert into blogs (title, content, userId, comments) values (?,?,?,?)`,
		[title, content, userId, comments]
	)
	// 返回
	if (insertData.affectedRows) {
		ctx.body = {
			code: 0,
			msg: 'success',
			data: { insertId: insertData.insertId }
		}
	} else {
		ctx.body = {
			code: -1,
			msg: '添加失败'
		}
	}
})

// 3. 博客修改接口
router.put('/api/blogs/:articleId', async (ctx, next) => {
	// 接收参数
	const { articleId } = ctx.params
	const { title, content, comments = '' } = ctx.request.body
	//
	const updateData = await exec(
		`update blogs set title=?, content=?, comments=? where id=?`,
		[title, content, comments, articleId]
	)
	if (updateData.affectedRows) {
		ctx.body = {
			code: 0,
			msg: '修改成功'
		}
	} else {
		ctx.body = {
			code: -1,
			msg: '修改失败'
		}
	}
})

// 4. 博客删除接口 更改状态实现删除 status 1 存在 2 删除
router.delete('/api/blogs/:deleteId', async (ctx, next) => {
	const { deleteId } = ctx.params
	const deleteData = await exec(`update blogs set status=? where id=?`, [
		2,
		deleteId
	])
	if (deleteData.affectedRows) {
		ctx.body = {
			code: 0,
			msg: '删除成功'
		}
	} else {
		ctx.body = {
			code: -1,
			msg: '删除失败'
		}
	}
})

module.exports = router
